package com.orange.framework.config;


import com.orange.framework.interceptor.ApiSecurityInterceptor;
import com.orange.framework.interceptor.SignValidateInterceptor;
import com.orange.framework.interceptor.TokenInterceptor;
import com.orange.framework.wrapper.CachedBodyHttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;

/**
 * 全局过滤器注册
 *
 * @Author YWF
 * @Date 2025/5/26 15:25
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    private final static Logger logger = LoggerFactory.getLogger(InterceptorConfig.class);

    private final static String pathPatterns = "/*/**";

    private static final String[] excludePathPatterns = {"/**/user/login", "/**/user/vLogin"};

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //请求头参数校验
        registry.addInterceptor(signAndHeaderParamsCheckInterceptor());
        ////token校验
        registry.addInterceptor(tokenInterceptor()).addPathPatterns(pathPatterns)
                .excludePathPatterns(excludePathPatterns);
        registry.addInterceptor(apiSecurityInterceptor());
    }

    @Bean
    public TokenInterceptor tokenInterceptor() {
        return new TokenInterceptor();
    }

    @Bean
    public SignValidateInterceptor signAndHeaderParamsCheckInterceptor() {
        return new SignValidateInterceptor();
    }

    @Bean
    public ApiSecurityInterceptor apiSecurityInterceptor() {
        return new ApiSecurityInterceptor();
    }


    /**
     * 注册过滤器，把ServletRequest转换为CachedBodyHttpServletRequest
     *
     * @return
     */
    @Bean
    public Filter requestWrapperFilter() {
        return (request, response, chain) -> {
            if (request instanceof HttpServletRequest) {
                CachedBodyHttpServletRequest cacheRequest = new CachedBodyHttpServletRequest((HttpServletRequest) request);
                chain.doFilter(cacheRequest, response);
            } else {
                chain.doFilter(request, response);
            }
        };
    }


}
